import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute } from '@angular/router';
import { NzMessageService } from 'ng-zorro-antd/message';
import { NzModalService } from 'ng-zorro-antd/modal';
import { customizedDescentStatusArr, customizedOrderStatusArr } from '../customized-coupon-manage.pipe';
import { PermissionService } from '../../../../service/permission.service';
import { CustomizedCouponService } from '../services/customized-coupon.service';
import { CustomizeDescentService } from '../services/customized-descent.service';

@Component({
  selector: 'app-customized-descent-list',
  templateUrl: './customized-descent-list.component.html',
  styleUrls: ['./customized-descent-list.component.scss']
})
export class CustomizedDescentListComponent implements OnInit {
  // 路由缓存恢复时
  static updateCache: any = null;

  typeOptions: any = [
    {value: 1, label: '满减'},
    {value: 2, label: '满折'},
    {value: 3, label: '多件折扣'}
  ];
  statusOptions: any = customizedDescentStatusArr.filter((item: any) => ![6, 7].includes(item.value));
  searchOptions = [
    { type: 1, labelText: '直降促销', valueKey: 'name', value: '', placeholder: '请输入ID/名称' },
    {
      type: 2,
      labelText: '类型',
      valueKey: 'type',
      value: [],
      multiple: true,
      selectOptions: [...this.typeOptions],
    },
    {
      type: 2,
      labelText: '状态',
      valueKey: 'status',
      value: [],
      multiple: true,
      selectOptions: this.statusOptions,
    }
  ];
  searchParams: any = {};

  tableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 20,
    total: 0
  };

  categoryOptions: any = []; // 适用品类

  /**
   * 直降记录 Modal
   * ----------------------------------------------------------------
   */
  isUserVisible = false;
  userCouponItem: any = {};
  userCouponTableParams: any = {
    loading: false,
    tableData: [],
    page: 1,
    pageSize: 10,
    total: 0
  };
  userLoading = false;
  recordOrderStatusOptions: any = [
    {value: 2, label: '待付款'},
    {value: 7, label: '待发货'},
    {value: 8, label: '待收货'},
    {value: 9, label: '交易完成'},
    {value: 10, label: '支付超时'},
    {value: 11, label: '客服取消'},
    {value: 12, label: '客户取消'},
    {value: 16, label: '交易结束'}
  ];
  userCouponSearch = [
    { type: 1, labelText: '订单编号', valueKey: 'orderNum', value: '' },
    { type: 1, labelText: '用户ID', valueKey: 'userId', value: '' },
    {
      type: 2,
      labelText: '状态',
      valueKey: 'statusStr',
      value: [],
      multiple: true,
      notTostr: false,
      selectOptions: this.recordOrderStatusOptions
    },
    { type: 3, labelText: '下单时间', valueKey: ['orderBeginTime', 'orderEndTime'], value: [], isTimeSelect: true },
    { type: 3, labelText: '付款时间', valueKey: ['createPayTime', 'endPayTime'], value: [], isTimeSelect: true }
  ];
  userCouponParams: any = {};
  recordStatusSelected: any[] = [];

  constructor(
    private message: NzMessageService,
    private router: Router,
    private modal: NzModalService,
    public permission: PermissionService,
    private customizedCouponService: CustomizedCouponService,
    private services: CustomizeDescentService
  ) { }

  ngOnInit(): void {
    this.loadAdzGoodTypeList();
    CustomizedDescentListComponent.updateCache = () => {
      this.loadAdzGoodTypeList();
      this.loadTable();
    }
  }

  // 查询适用品类
  async loadAdzGoodTypeList() {
    const {code, data, message}: any = await this.customizedCouponService.getAdzGoodTypeList();
    if (code === 0) {
      this.categoryOptions = data || [];
    } else {
      this.message.error(message);
    }
  }

  async loadTable() {
    let params = {
      ...this.searchParams,
      page: this.tableParams.page,
      pageSize: this.tableParams.pageSize
    }
    this.tableParams.loading = true;
    const res: any = await this.services.getdescentList(params);
    this.tableParams.loading = false;

    if (res.code === 0) {
      const { records, total } = res.data || {};
      this.tableParams.tableData = records || [];
      this.tableParams.total = total || 0;
    } else {
      this.message.error(res.message);
    }
  }

  queryData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  resetData(params: any) {
    this.searchParams = params;
    this.tableParams.page = 1;
    this.loadTable();
  }

  // PageIndex Change
  onPageIndexChange(index: number) {
    this.tableParams.page = index;
    this.loadTable();
  }
  
  // PageSize Change
  onPageSizeChange(sizeNum: number) {
    this.tableParams.page = 1;
    this.tableParams.pageSize = sizeNum;
    this.loadTable();
  }

  /**
   * 页面跳转
   * @param type 0：新增 1：编辑 2：查看 3：复制
   * @param item 
   */
  jumpPage(type: number, item?: any) {
    let url = type === 2 ? '/customization/customized-descent-details' : '/customization/customized-descent-edit';
    let obj: any = {
      type
    };
    if ([1, 2, 3].includes(type)) {
      obj.id = item.id
    }
    this.router.navigate([url],{
      queryParams: obj
    })
  }

  /**
   * 停止活动 | 删除活动 | 启用
   * @param item 
   * @param status 4：停止 8：删除 1：启用
   */
  async stopDelActivity(item: any, status: number) {
    let params = {
      id: item.id,
      status: status
    }
    const { code, message }: any = await this.services.updateDescentItem(params);
    if (code === 0) {
      this.message.success('操作成功');
      this.loadTable();
    } else {
      this.message.error(message);
    }
  }

  // 发布
  async releaseItem(item: any) {
    let params = {
      id: item.id,
      status: 1
    }
    const {code, message}: any = await this.services.updateDescentItem(params);
    if (code === 0) {
      this.message.success('发布成功');
      this.loadTable();
    } else {
      this.message.error(message);
    }
  }

  /**
   * ----------------------------------------------------------------
   * 直降记录Table
   * ----------------------------------------------------------------
   */
  async loadRecordTable() {
    let params = {
      ...this.userCouponParams,
      activityId: this.userCouponItem.id,
      page: this.userCouponTableParams.page,
      pageSize: this.userCouponTableParams.pageSize
    }
    this.userCouponTableParams.loading = true;
    const {code, data, message}: any = await this.services.getDescentRecordList(params);
    this.userCouponTableParams.loading = false;

    if (code === 0) {
      const {records, total} = data || {};
      this.userCouponTableParams.tableData = records || [];
      this.userCouponTableParams.total = total || 0;
    } else {
      this.message.error(message);
    }
  }

  couponQueryData(params: any) {
    this.userCouponParams = params;
    // 待发货状态处理
    let tempStatus = params.statusStr ? params.statusStr.split(',') : [];
    if (tempStatus.includes('7')) {
      tempStatus.push('3', '4', '5', '6');
    } else {
      tempStatus = tempStatus.filter((item: any) => !['3', '4', '5', '6'].includes(item));
    }
    this.userCouponParams.statusStr = tempStatus.join(',');
    this.userCouponTableParams.page = 1;
    this.loadRecordTable();
  }

  couponResetData(params: any) {
    this.userCouponParams = params;
    this.userCouponTableParams.page = 1;
    this.loadRecordTable();
  }

  showUserCouponModal(item: any) {
    this.userCouponItem = item || {};
    this.isUserVisible = true;
  }

  // PageIndex Change
  recordIndexChange(index: number) {
    this.userCouponTableParams.page = index;
    this.loadRecordTable();
  }
  
  // PageSize Change
  recordSizeChange(sizeNum: number) {
    this.userCouponTableParams.page = 1;
    this.userCouponTableParams.pageSize = sizeNum;
    this.loadRecordTable();
  }

  // 适用品类
  categoryTypeFilter(str: string) {
    if (this.isEmpty(str)) {
      return '-'
    } else {
      if (str === '0') {
        return '全部'
      } else {
        let strArr = str.split(',').map((m: any) => +m);
        let tempArr: any = [];
        this.categoryOptions.forEach((item: any) => {
          if (strArr.includes(item.groupId)) {
            tempArr.push(item.textureName);
          }
        })
        return tempArr.join('、');
      }
    }
  }

  // is Empty
  isEmpty(val: any) {
    if (val === '' || val === undefined || val === null) {
      return true;
    } else {
      return false;
    }
  }
}
